/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "GeometryViewComponentInstance.h"
#include "Props.h"
#include <folly/dynamic.h>

using namespace rnoh;

GeometryViewComponentInstance::GeometryViewComponentInstance(Context context)
    : CppComponentInstance(std::move(context))
{
    m_geometryViewNode.setGeometryViewNodeDelegate(this);
}

void GeometryViewComponentInstance::onChildInserted(ComponentInstance::Shared const &childComponentInstance,
                                                    std::size_t index)
{
    CppComponentInstance::onChildInserted(childComponentInstance, index);
    m_geometryViewNode.insertChild(childComponentInstance->getLocalRootArkUINode(), index);
}

GeometryViewNode &GeometryViewComponentInstance::getLocalRootArkUINode() { return m_geometryViewNode; }

void GeometryViewComponentInstance::onChildRemoved(ComponentInstance::Shared const &childComponentInstance)
{
    CppComponentInstance::onChildRemoved(childComponentInstance);
    m_geometryViewNode.removeChild(childComponentInstance->getLocalRootArkUINode());
}

void GeometryViewComponentInstance::onPropsChanged(SharedConcreteProps const &props)
{
    CppComponentInstance::onPropsChanged(props);
    m_geometryViewNode.setNodeID(props->geometryViewID);
    if (!m_props || props->geometryViewID != m_props->geometryViewID) {
        m_geometryViewNode.setGeometryViewID(props->geometryViewID);
    }
}

void GeometryViewComponentInstance::onGeometryViewClick()
{
    facebook::react::GeometryViewEventEmitter::OnGeometryViewClick m_onGeometryViewClick;
    m_onGeometryViewClick.isGeometryView = true;
    m_onGeometryViewClick.type = "custom";
    m_eventEmitter->onGeometryViewClick(m_onGeometryViewClick);
}

void GeometryViewComponentInstance::handleCommand(std::string const &commandName, folly::dynamic const &args)
{
    if (commandName == "changeGeometryTransitionID") {
        std::string geometryViewID = args[0].asString();
        LOG(INFO) << "GeometryView " << "changeGeometryTransitionID(" << geometryViewID << ")";
        m_geometryViewNode.setGeometryViewID(geometryViewID);
        m_geometryViewNode.setNodeID(geometryViewID);
    }
}
